package hostsystem;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class signinHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		HttpSession session = req.getSession();
		String account_id = req.getParameter("account_id");
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		String password1 = req.getParameter("password1");
		String type = req.getParameter("type");
		String epass = SetMD5.getMD5(password);
		//System.out.println("epass "+epass);
		Connection con = hostdb.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = con.prepareStatement("select * from users where account_id=?");
			ps.setString(1, account_id);
			rs = ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		session.setAttribute("islogin", null);
		session.setAttribute("signin", true);
		try {
			if (rs.next()) {
				// user name is not valid
				ps.close();
				con.close();
				// System.out.println("user already exists");
				req.setAttribute("msg", "user already exists!");
				req.getRequestDispatcher("/msg.jsp").forward(req, resp);
			} else {
				// ps.close();
				if (password.equals(password1)) {
					if (password.equals("") || password.equals(null)) {
						ps.close();
						con.close();
						req.setAttribute("msg", "Please input password!");
						req.getRequestDispatcher("/msg.jsp").forward(req, resp);
					} else {
						ps = con.prepareStatement("insert into users (account_id,password,name,type,status) values(?,?,?,?,1)");
						ps.setString(1, account_id);
						ps.setString(2, epass);
						ps.setString(3, name);
						ps.setString(4, type);
						ps.executeUpdate();
						con.commit();
						ps.close();
						con.close();
						resp.sendRedirect("login.html");
					}
				} else {
					ps.close();
					con.close();
					req.setAttribute("msg", "Password not match!");
					req.getRequestDispatcher("/msg.jsp").forward(req, resp);
				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.sendRedirect("login.html");
	}
}